import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { fileUploadAPI } from '~/api/fileUpload'

export function useFileUpload() {
  const selectedFile = ref(null)
  const uploading = ref(false)
  const accept = ref('.jpg,.png,.jpeg')

  const handleFileChange = (event) => {
    const file = event.target.files[0]
    if (!file) return

    const fileType = file.type.split('/')[1]
    const maxSize = 5 * 1024 * 1024 // 5MB

    // 验证文件类型
    if (!accept.value.includes(fileType)) {
      ElMessage.error('请上传 JPG、PNG 或 JPEG 格式的图片')
      return
    }

    // 验证文件大小
    if (file.size > maxSize) {
      ElMessage.error('图片大小不能超过 5MB')
      return
    }

    selectedFile.value = file
  }

  const triggerFileSelect = (acceptType = '') => {
    if (acceptType) {
      accept.value = acceptType
    } else {
      accept.value = '.jpg,.png,.jpeg'
    }
    
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.accept = accept.value
    fileInput.multiple = false
    fileInput.onchange = handleFileChange
    fileInput.click()
  }

  // 上传文件
  const uploadFile = async (file = null) => {
    const fileToUpload = file || selectedFile.value
    if (!fileToUpload) {
      ElMessage.error('请选择要上传的文件')
      return null
    }

    try {
      uploading.value = true
      const formData = new FormData()
      formData.append('file', fileToUpload)
      
      const response = await fileUploadAPI(formData)
      
      if (response.code === 200) {
        ElMessage.success('上传成功')
        // 返回后端的 ossId，用于提交给业务接口
        return response.data.ossId
      } else {
        ElMessage.error(response.message || '上传失败')
        return null
      }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error('上传失败，请重试')
      return null
    } finally {
      uploading.value = false
    }
  }

  return {
    selectedFile,
    uploading,
    triggerFileSelect,
    uploadFile
  }
}